﻿using System;
using System.Collections.Generic;
using FairyGUI;
using UnityEngine;
public class FEditBiologyMediator : MyWindow
{
    FSelectListMediator _selectImgPanel;
    GTextField _imgText;
    GTextField _idText;
    GTextInput _nameEditBox;
    GTextInput _bloodEditBox;
    GTextInput _defenseEditBox;
    GTextInput _attackEditBox;
    GTextInput _descriptEditBox;
    FBiology _realBiology;

    GList _cardList;
    GList _equipmentList;
    GList _dialogueList;

    GComboBox _typeDownList;

    Biology _biologyData;
    Biology _preBiologyData;
    int _biologyIndex;

    List<Weapon> _weaponDataList;
    List<Card> _cardDataList;
    List<string> _delDialogueList;
    int _dialogueIndex;
    Controller _equipmentTypeCtrl;


    public FEditBiologyMediator()
    {
        this.contentPane = UIPackage.CreateObject("BiologyPackage", "EditBiologyPanel").asCom;
        //组件获取
        _imgText = this.contentPane.GetChild("imgText").asTextField;
        _realBiology = (FBiology)this.contentPane.GetChild("realBiology");
        _idText = this.contentPane.GetChild("idText").asTextField;
        _nameEditBox = this.contentPane.GetChild("nameEditBox").asTextInput;
        _bloodEditBox = this.contentPane.GetChild("bloodEditBox").asTextInput;
        _defenseEditBox = this.contentPane.GetChild("defenseEditBox").asTextInput;
        _attackEditBox = this.contentPane.GetChild("attackEditBox").asTextInput;
        _descriptEditBox = this.contentPane.GetChild("descriptEditBox").asCom.GetChild("title").asTextInput;
        _equipmentList = this.contentPane.GetChild("equipmentList").asList;
        _cardList = this.contentPane.GetChild("cardtList").asList;
        _dialogueList = this.contentPane.GetChild("dialogueList").asList;
        _typeDownList = this.contentPane.GetChild("typeDownList").asComboBox;
        _equipmentTypeCtrl = this.contentPane.GetController("EquipmentType");

        //下拉框
        _typeDownList.onChanged.Add(OnTypeDownListChange);
        //文本
        _bloodEditBox.onFocusOut.Add(OnBloodEditBoxOut);
        _defenseEditBox.onFocusOut.Add(OnDefenseEditBoxOut);
        _attackEditBox.onFocusOut.Add(OnAttackEditBoxOut);
        _equipmentTypeCtrl.onChanged.Add(OnEquipmentTypeChange);
        //按钮事件监听
        this.contentPane.GetChild("exitBtn").onClick.Add(OnExitPanel);
        this.contentPane.GetChild("saveBtn").onClick.Add(OnSaveBtnClick);
        this.contentPane.GetChild("delBtn").onClick.Add(OnDelBtnClick);
        this.contentPane.GetChild("selectImgBtn").onClick.Add(OnSelectImgBtn);
        this.contentPane.GetChild("addWeaponBtn").onClick.Add(OnAddWeaponBtn);
        this.contentPane.GetChild("addCardBtn").onClick.Add(OnAddCardBtn);
        this.contentPane.GetChild("addDialogueBtn").onClick.Add(OnAddDialogueBtn);

        _equipmentList.itemRenderer = RenderEquipmentListItem;
        _cardList.itemRenderer = RenderCardListItem;
        _dialogueList.itemRenderer = RenderDialogueListItem;
        //存放删除的对白
        _delDialogueList = new List<string>();
    }

    private void OnEquipmentTypeChange(EventContext context)
    {
        FreshEquipment();
    }

    private void OnDefenseEditBoxOut(EventContext context)
    {
        if(_defenseEditBox.text == "") _defenseEditBox.text = "0";
        _biologyData.defense = System.Convert.ToInt32(_defenseEditBox.text);
    }

    private void OnAttackEditBoxOut(EventContext context)
    {
        if(_attackEditBox.text == "") _attackEditBox.text = "0";
        _biologyData.attack = System.Convert.ToInt32(_attackEditBox.text);
    }

    private void OnBloodEditBoxOut(EventContext context)
    {
        if(_bloodEditBox.text == "") _bloodEditBox.text = "0";
        _biologyData.blood = System.Convert.ToInt32(_bloodEditBox.text);
    }

    private void OnDialogueTypeChange(EventContext context)
    {
        var _sender = (GComboBox)context.sender;
        var index = _dialogueList.GetChildIndex(_sender.parent);
        _biologyData.dialogueList[index].type = (GMConfig.DialogueType)System.Enum.Parse(typeof(GMConfig.DialogueType),_sender.value);
    }

    private void RenderDialogueListItem(int index, GObject item)
    {
        item.asCom.GetChild("text").text = _biologyData.dialogueList[index].GetStr();
        item.asCom.GetChild("selectText").text = _biologyData.dialogueList[index].audio;

        item.asCom.GetChild("removeBtn").onClick.Add(OnRemoveDialogueBtn);
        item.asCom.GetChild("selectBtn").onClick.Add(OnSelectDialogueAudioBtn);
        var dialogueTypeDownList = item.asCom.GetChild("title").asComboBox;
        dialogueTypeDownList.selectedIndex = (int)_biologyData.dialogueList[index].type;
        dialogueTypeDownList.onChanged.Add(OnDialogueTypeChange);
    }

    private void OnSelectDialogueAudioBtn(EventContext context)
    {
        _dialogueIndex = _dialogueList.GetChildIndex(((GObject)context.sender).parent);
        _selectImgPanel = (FSelectListMediator)FUIMain.ShowPanel(GMConfig.PanelType.SelectAudioPanel);
        _selectImgPanel.InitData("AudioPackage",PackageItemType.Sound,(url) => {
            _biologyData.dialogueList[_dialogueIndex].audio = UIPackage.GetItemByURL(url.ToString()).name;
            RenderDialogueListItem(_dialogueIndex,_dialogueList.GetChildAt(_dialogueIndex));
        });
    }

    private void OnRemoveDialogueBtn(EventContext context)
    {
        var index = _dialogueList.GetChildIndex(((GObject)context.sender).parent);
        _delDialogueList.Add(_biologyData.dialogueList[index].dialogueKey);
        _biologyData.RemoveDialogueAt(index);
        _dialogueList.RemoveChildToPoolAt(index);
    }
    /// <summary>
    /// 添加对白
    /// </summary>
    /// <param name="context"></param>
    private void OnAddDialogueBtn(EventContext context)
    {
        var index = _biologyData.AddDialogue();
        var item = _dialogueList.AddItemFromPool();
        RenderDialogueListItem(index,item);
    }

    private void RenderEquipmentListItem(int index, GObject item)
    {
        item.text = _weaponDataList[index].GetWeaponName();
        item.asCom.GetChild("removeBtn").onClick.Add(OnRemoveWeaponBtn);
        item.asCom.GetChild("title").onClick.Add(OnEditWeaponClick);
    }
    private void OnRemoveWeaponBtn(EventContext context)
    {
        var index = _equipmentList.GetChildIndex(((GObject)context.sender).parent);
        _biologyData.RemoveWeapon(_equipmentTypeCtrl.selectedIndex,_weaponDataList[index].id);
        _weaponDataList.RemoveAt(index);
        // _equipmentList.RemoveChildrenToPool();
        _equipmentList.RemoveChildToPoolAt(index);
    }
    private void OnEditWeaponClick(EventContext context)
    {
        var panel = (FEditWeaponMediator)FUIMain.ShowPanel(GMConfig.PanelType.EditWeaponPanel);
        var index = _equipmentList.GetChildIndex(((GObject)context.sender).parent);
        panel.InitData(_weaponDataList[index],WeaponMO.GetWeaponIndex(_weaponDataList[index]));
    }
    /// <summary>
    /// 添加武器
    /// </summary>
    /// <param name="context"></param>
    private void OnAddWeaponBtn(EventContext context)
    {
        FUIMain.ShowPanel(GMConfig.PanelType.SelectWeaponList,(res) => {
            FUIMain.ClosePanel(GMConfig.PanelType.SelectWeaponList);
            if(res != null) {
                _biologyData.AddWeapon(_equipmentTypeCtrl.selectedIndex,res.ToString());
                var weapon = WeaponMO.GetWeaponById(res.ToString());
                if(weapon != null && !_weaponDataList.Contains(weapon)){
                    _weaponDataList.Add(weapon);
                    var item = _equipmentList.AddItemFromPool();
                    RenderEquipmentListItem(_weaponDataList.Count - 1,item);
                }
            }
        });
    }

    private void RenderCardListItem(int index, GObject item)
    {
        item.text = _cardDataList[index].GetCardName();
        item.asCom.GetChild("removeBtn").onClick.Add(OnRemoveCardBtn);
        item.asCom.GetChild("title").onClick.Add(OnEditCardClick);
    }
    private void OnRemoveCardBtn(EventContext context)
    {
        var index = _cardList.GetChildIndex(((GObject)context.sender).parent);
        _biologyData.RemoveCard(_equipmentTypeCtrl.selectedIndex,_cardDataList[index].id);
        _cardDataList.RemoveAt(index);
        // _cardList.RemoveChildrenToPool();
        _cardList.RemoveChildToPoolAt(index);
    }
    private void OnEditCardClick(EventContext context)
    {
        var panel = (FEditCardPanel)FUIMain.ShowPanel(GMConfig.PanelType.EditCardPanel);
        var index = _cardList.GetChildIndex(((GObject)context.sender).parent);
        panel.InitData(_cardDataList[index],CardMO.GetCardIndex(_cardDataList[index]));
    }
    /// <summary>
    /// 添加卡牌
    /// </summary>
    /// <param name="context"></param>
    private void OnAddCardBtn(EventContext context)
    {
        FUIMain.ShowPanel(GMConfig.PanelType.SelectCardList,(res) => {
            FUIMain.ClosePanel(GMConfig.PanelType.SelectCardList);
            if(res != null) {
                _biologyData.AddCard(_equipmentTypeCtrl.selectedIndex,res.ToString());
                var card = CardMO.GetCardById(res.ToString());
                if(card != null && !_cardDataList.Contains(card)){
                    _cardDataList.Add(card);
                    var item = _cardList.AddItemFromPool();
                    RenderCardListItem(_cardDataList.Count - 1,item);
                }
            }
        });
    }

    protected override void OnInit()
    {
        base.OnInit();
        this.Center();
    }
    /// <summary>
    /// 编写其他需要在窗口显示时处理的业务逻辑。
    /// </summary>
    protected override void OnShown()
    {
        base.OnShown();
 
    }
    /// <summary>
    /// 定时器
    /// </summary>
    protected override void OnUpdate()
    {
        base.OnUpdate();
        _realBiology.Fresh();
    }
    public void InitData(Biology biology,int biologyIndex)
    {
        CheckDataChange(() => {
            ResetPanel();
            _preBiologyData = biology;
            _biologyData = biology.DeepClone();
            _biologyIndex = biologyIndex;

            _idText.text = _biologyData.id;
            _realBiology.InitData(_biologyData,false);
            _imgText.text = _biologyData.img;
            _nameEditBox.text = _biologyData.GetBiologyName();
            _descriptEditBox.text = _biologyData.GetBiologyDescript();
            _bloodEditBox.text = _biologyData.blood.ToString();
            _defenseEditBox.text = _biologyData.defense.ToString();
            _attackEditBox.text = _biologyData.attack.ToString();
            _typeDownList.selectedIndex = (int)_biologyData.type;

            FreshEquipment();
            //对白
            _dialogueList.RemoveChildrenToPool();
            _dialogueList.numItems = _biologyData.dialogueList.Count;            
        });
    }

    private void FreshEquipment()
    {
        //装备列表
        _weaponDataList = new List<Weapon>();
        var biologyEquipment = _biologyData.GetEquipment(_equipmentTypeCtrl.selectedIndex);
        foreach(var item in biologyEquipment.weaponList){
            var weapon = WeaponMO.GetWeaponById(item);
            if(weapon != null) _weaponDataList.Add(weapon);
        }
        _equipmentList.RemoveChildrenToPool();
        _equipmentList.numItems = _weaponDataList.Count;
        //卡牌列表
        _cardDataList = new List<Card>();
        foreach(var item in biologyEquipment.cardList){
            var card = CardMO.GetCardById(item);
            if(card != null) _cardDataList.Add(card);
        }
        _cardList.RemoveChildrenToPool();
        _cardList.numItems = _cardDataList.Count;
    }

    private void ResetPanel(){

    }
    /// <summary>
    /// 编写其他需要在窗口隐藏时处理的业务逻辑。
    /// </summary>
    protected override void OnHide()
    {
        base.OnHide();
        if (_selectImgPanel != null && _selectImgPanel.isShowing) _selectImgPanel.Hide();
    }
    private void OnExitPanel()
    {
        CheckDataChange(() => {
            _delDialogueList.Clear();
            _preBiologyData = null;
            this.Hide();
        });
    }
    private void CheckDataChange(ZeroDeletegate cb){
        if(_preBiologyData == null) {
            cb();
            return;
        }
        var isEqual = Utils.CompareObject(_preBiologyData,_biologyData);
        var isChange = this.TextIsChange(false);
        //判断是否有改变
        if(!isEqual || isChange){
            FUIMain.TipPanel("生物数据发生改变，确定放弃本次修改？", (status) => {
                if ((int)status == 1)
                {
                    cb();
                }
            });
        }else{
            cb();
        }
    }
    private void OnSelectImgBtn()
    {
        _selectImgPanel = (FSelectListMediator)FUIMain.ShowPanel(GMConfig.PanelType.SelecImgtPanel);
        _selectImgPanel.InitData("CardImgPackage",PackageItemType.Image,OnSelectImgCB);
    }
    private void OnSelectImgCB(object imgUrl)
    {
        _imgText.text = imgUrl.ToString();
        _biologyData.img = imgUrl.ToString();
        _realBiology.Fresh();
    }
    /// <summary>
    /// 生物类型变化
    /// </summary>
    private void OnTypeDownListChange()
    {
        var biologyType = (GMConfig.BiologyType)Enum.Parse(typeof(GMConfig.BiologyType),_typeDownList.value);
        _biologyData.type = biologyType;
        Debug.Log(biologyType);
    }
    /// <summary>
    /// 判断文字是否发生改变
    /// </summary>
    /// <returns></returns>
    private bool TextIsChange(bool isSave = true){
        var isChange = false;
        //判断是否需要重新保存名字
        if(_preBiologyData.GetBiologyName() != _nameEditBox.text)
        {
            if(isSave) LTLocalization.AddText(_preBiologyData.name, _nameEditBox.text);
            isChange = true;
        }
        //判断是否需要重新保存介绍
        if(_preBiologyData.GetBiologyDescript() != _descriptEditBox.text)
        {
            if(isSave) LTLocalization.AddText(_preBiologyData.descript, _descriptEditBox.text);
            isChange = true;
        }
        for(int i = 0; i < _biologyData.dialogueList.Count;i++){
            var item = _biologyData.dialogueList[i];
            var text = _dialogueList.GetChildAt(i).asCom.GetChild("text").text;
            if(item.GetStr() != text) {
                if(isSave) LTLocalization.AddText(item.dialogueKey,text);
                isChange = true;
            }
        }
        return isChange;
    }
    /// <summary>
    /// 保存生物数据
    /// </summary>
    private void OnSaveBtnClick()
    {
        var isChange = this.TextIsChange();
        //删除已经删除的对白文本
        foreach(var item in _delDialogueList){
            Debug.Log(item + "删除");
            LTLocalization.DelKey(item);
            isChange = true;
        }
        _delDialogueList.Clear();
        if(isChange) LTLocalization.SaveDataToCSV();
        _preBiologyData = _biologyData.DeepClone();
        var isOk = FBiologyListMediator.SaveBiology(_preBiologyData,_biologyIndex);
        var str = "保存成功！";
        if(!isOk) str = "保存失败！";
        FUIMain.TipPanel(str);
    }
    /// <summary>
    /// 保存生物数据
    /// </summary>
    private void OnDelBtnClick()
    {
        FUIMain.TipPanel("确定要删除本张生物？", (status) => {
            if ((int)status == 1)
            {
                FBiologyListMediator.DelBiology(_biologyIndex);
                _preBiologyData = null;
                this.Hide();
            }
        });
    }
    /// <summary>
    /// 获得所有可选类型
    /// </summary>
    /// <returns></returns>
    public Dictionary<string,List<string>> GetTypeDict()
    {
        var dict = new Dictionary<string, List<string>>();
        //生物类型
        var _typeTextList = GetChildrenText(_typeDownList,true);
        dict.AddOrReplace("typeTextList", _typeTextList);

        return dict;
    }
    /// <summary>
    /// 获得指定控件子物体的text
    /// </summary>
    /// <param name="gComponent"></param>
    /// <returns></returns>
    private List<string> GetChildrenText(GComponent gComponent,bool isCombox = false)
    {
        var textList = new List<string>();
        if (isCombox)
        {
            var _gComponent = (GComboBox)gComponent;
            for (int i = 0; i < _gComponent.items.Length; i++)
            {
                textList.Add(_gComponent.items[i]);
            }
        }
        else
        {
            for (int i = 0;i < gComponent.numChildren; i++)
            {
                textList.Add(gComponent.GetChildAt(i).text);
            }
        }
        return textList;
    }
}

